package com.boarsoft.boar.soagov.face.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.soagov.entity.ObjFaces;
import com.boarsoft.boar.soagov.face.ObjFacesBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("objFacesBiz")
public class ObjFacesBizImpl extends SimpleBizImpl implements ObjFacesBiz {
	@Override
	@Transactional(readOnly = true)
	public ObjFaces find(String objId, String faceId) {
		String sb = "and objId='" + objId + "' and faceId='" + faceId + "'";
		return (ObjFaces) dao.find(ObjFaces.class, sb);
	}

	@Override
	@Transactional(readOnly = true)
	public PagedResult<ObjFaces> list(String objId, String faceId, String objType,
			String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		if (Util.strIsNotEmpty(objId)) {
			sb.append(" and objId='").append(objId).append("'");
		} else if (Util.strIsNotEmpty(faceId)) {
			sb.append(" and faceId='").append(faceId).append("'");
		}
		if (Util.strIsNotEmpty(objType)) {
			sb.append(" and objType='").append(objType).append("'");
		}
		int total = dao.getTotal(ObjFaces.class, sb.toString());
		sb.setLength(0);
		sb.append("select n from ").append(ObjFaces.class.getName());
		if (Util.strIsNotEmpty(objId)) {
			sb.append(" n join fetch n.face f left join fetch f.params where n.objId='");
			sb.append(objId).append("'");
		} else if (Util.strIsNotEmpty(faceId)) {
			sb.append(" n join fetch n.com where n.faceId='");
			sb.append(faceId).append("'");
		}
		List<ObjFaces> lt = dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<ObjFaces>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void delete(String id) {
		dao.delete(ObjFaces.class, id);
	}

	@Override
	@Transactional
	public ReplyInfo<Object> save(ObjFaces p) {
		if (Util.strIsNotEmpty(p.getId())) {
			dao.merge(p);
		} else {
			StringBuilder sb = new StringBuilder();
			sb.append("select id from ").append(ObjFaces.class.getName());
			sb.append(" where objId='").append(p.getObjId());
			sb.append("' and faceId='").append(p.getFaceId()).append("'");
			String id = (String) dao.getValue(sb.toString());
			if (Util.strIsNotEmpty(id)) {
				p.setId(id);
				dao.merge(p);
			} else {
				dao.save(p);
			}
		}
		return new ReplyInfo<Object>(true, p.getId());
	}

	@Override
	@Transactional(readOnly = true)
	public ObjFaces get(String id) {
		return (ObjFaces) dao.get(ObjFaces.class, id);
	}

	@Override
	@Transactional(readOnly = true)
	public List<ObjFaces> list(String objId) {
		return dao.list(ObjFaces.class, "and objId='" + objId + "'");
	}
}